<template>
  
  <div class="login-container" style="display: flex; flex-direction: column; justify-content: center; align-items: center">
    <img src="../assets/log.png" alt="" width="242" height="90" style="margin-bottom: 20px;">
    <div class="login-form">
      <h2 style="font-size: 18px;">智慧厨管家云平台</h2>
      <el-form 
      :model="loginForm" 
      @submit.prevent="handleLogin(ruleFormRef)" 
      ref="ruleFormRef"
      status-icon
      :rules="rules"
      >
        <el-form-item prop="user_name">
          <el-input v-model="loginForm.user_name" placeholder="用户名" prefix-icon="User" />
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="Lock" />
        </el-form-item>

        <el-form-item class="login_button">
          <el-button type="primary" native-type="submit" :loading="loading">登录</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
// 状态管理,自己处理（保存用户信息、token等）
import { useAuthStore } from '../stores/userStore'
import { ElMessage } from 'element-plus'
import { login } from '../api/user' // API

// 表单对象
const ruleFormRef = ref(null)

// 表单数据
const loginForm = reactive({
  user_name: 'admin',
  password: ''
})

// 表单验证（自定义）
// 验证用户名
const validateUserName = (rrule,value,callback) => {
  if (value === '') {
    callback(new Error('用户名不能为空，请输入!'))
  } else {
    callback()
  }
} 
// 验证密码
const validatePass = (rule,value,callback) => {
  if (value === '') {
    callback(new Error('密码不能为空，请输入!'))
  } else {
    // 长度在6-12位之间且必须包含大小写字母和数字:^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,12}$
    const pwdRule = new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,12}$/)

    if (!pwdRule.test(loginForm.password)){
      callback(new Error('密码必须包含大小写字母和数字!'))
    }

    if (loginForm.password.length < 6 || loginForm.password.length > 12){
      callback(new Error('密码长度在6-12位之间!'))
    }
    callback()
  }
}
// 表单验证规则
const rules = reactive({
  user_name: [{ validator: validateUserName, trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
})

//按钮动画与路由
const loading = ref(false)
const router = useRouter()


// 状态管理
const authStore = useAuthStore()

// 登录
const handleLogin = (formEl) => {
  // if (!loginForm.user_name || !loginForm.password) {
  //   ElMessage.warning('请输入用户名和密码')
  //   return
  // }

  if (!formEl) return;

  // 验证表单
  formEl.validate(async (valid) => {
    if (valid) {
      // 开启动画
      loading.value = true
     
      try {
        // 登录请求
        const res = await login(loginForm)
        console.log(res)

        // 获取请求返回的数据
        const { data: { token, user_name, user_id, role_id } } = res;

        // 存储数据
        // utils.setStorage("token", token)
        // utils.setStorage("user_name", user_name)
        // utils.setStorage("user_id", user_id)
        // utils.setStorage("role_id", role_id)
        authStore.login({ token, user_name, user_id, role_id })

        // 关闭动画
        loading.value = false
        // 提示信息
        ElMessage.success('登录成功')
        // 登录成功后，跳转到首页
        router.push('/dashboard')
        
      } catch (error) {
        ElMessage.error(error.msg || '登录失败')
        loading.value = false
      }
    } else {
      console.log('登录表单验证未通过!')
    }
  })

}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style lang="less" scoped>
.login-container {
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  // background-color: #f0f2f5;
  // background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background: url('../assets/landing.avif');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;

  color: #ffffff;

  .login-form {
    width: 480px;
    padding: 30px;
    background: #346f91;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    h2 {
      text-align: center;
      margin-bottom: 30px;
      // color: #333;
    }
    
    // 表单样式
    .el-form{
      .el-form-item{
        margin-top: 26px;
        .el-input__inner { 
          background: #346f91;
          color: #ffffff;
        }
       :deep(.el-input__wrapper) {
          height: 43px;
          background: transparent;
          font-size: 16px;

          .el-input__inner{
            color: #ffffff;
            
          }
        }
        :deep(.el-form-item__content){
            display: flex;
            justify-content: center;

            .el-form-item__error { 
              // color: #ffffff;
              margin-top: 5px;
            }
        }

        &.login_button{
         
          :first-child{
            width: 32%;
            height: 40px;
            letter-spacing: 2px;
          }
          :last-child{
            height: 40px;
            width: 32%;
          }
          // 按钮样式
          :deep(.el-button>span){
            font-size: 14px;
            justify-content: center;
          }
        }

      }
    }
  }
}
</style>